package fun.coding.leetcode;

public class BestTimeToBuyAndSellStockIII {

	public static void main(String[] args) {
		BestTimeToBuyAndSellStockIII instance = new BestTimeToBuyAndSellStockIII();
		int[] a = {2, 5, 7, 1, 2, 9, 3};
		System.out.println(instance.maxProfit(a));
	}

	// this is a pattern, from left to right, right to left, and then combine those left and right
	// Hannoi problem, 2^n-1 steps to move n plates from A to C
	public int maxProfit(int[] prices) {
		if (prices == null || prices.length <= 1) return 0;
		
		int[] left = new int[prices.length];
		int[] right = new int[prices.length];
		
		// from left to right
		int min = Integer.MAX_VALUE;
		int localMaxProfit = 0;
		for (int i = 0; i < prices.length; i++) {
			if (prices[i] > min) {
				localMaxProfit = Math.max(localMaxProfit, prices[i] - min);
			} else {
				min = prices[i];
			}
			left[i] = localMaxProfit;
		}
		
		// from right to left
		int max = Integer.MIN_VALUE;
		// TODO: could left[i-1] as the localMaxProfit, that will make it more like DP.
		localMaxProfit = 0;
		for (int i = prices.length - 1; i >= 0; i--) {
			if (prices[i] < max) {
				localMaxProfit = Math.max(localMaxProfit, max - prices[i]); 
			} else {
				max = prices[i];
			}
			right[i] = localMaxProfit;
		}
		
		int globalMax = 0;
		for (int i = 0; i < prices.length; i++) {
			globalMax = Math.max(left[i] + right[i], globalMax);
		}
		
		return globalMax;
	}
	
	/*
	public class Solution {
	    public int maxProfit(int[] prices) {
	        if (prices == null || prices.length <= 1) {
	            return 0;
	        }

	        int[] left = new int[prices.length];
	        int[] right = new int[prices.length];

	        // DP from left to right;
	        left[0] = 0;
	        int min = prices[0];
	        for (int i = 1; i < prices.length; i++) {
	            min = Math.min(prices[i], min);
	            left[i] = Math.max(left[i - 1], prices[i] - min);
	        }

	        //DP from right to left;
	        right[prices.length - 1] = 0;
	        int max = prices[prices.length - 1];
	        for (int i = prices.length - 2; i >= 0; i--) {
	            max = Math.max(prices[i], max);
	            right[i] = Math.max(right[i + 1], max - prices[i]);
	        }

	        int profit = 0;
	        for (int i = 0; i < prices.length; i++){
	            profit = Math.max(left[i] + right[i], profit);  
	        }

	        return profit;
	    }
	}
	*/

}
